var ilts = {};

ilts.MAX_RESULTS_LIST = 10;
ilts.VIDEO_FEED_URL = 'http://gdata.youtube.com/feeds/api/videos';
//ilts.VIDEO_RELATED_URL = 'http://gdata.youtube.com/feeds/api/videos/%%videoid%%/related?v=2&alt=jsonc'
ilts.previousSearchTerm = '';
ilts.previousQueryType='all';
ilts.VIDEO_LIST_TABLE_CONTAINER_DIV = 'searchResultsVideoList';
ilts.VIDEO_LIST_CSS_CLASS = 'videoList';
ilts.THUMBNAIL_WIDTH = 80;
ilts.THUMBNAIL_HEIGHT = 72;
ilts.REFERRING_FEED_TYPE_MAIN = 'main';
ilts.jsonFeed_ = null;


ilts.QUERY_URL_MAP = {
//  'related' : ilts.VIDEO_RELATED_URL,
  'all' : ilts.VIDEO_FEED_URL
};



/**
 * Creates a script tag for retrieving a Google data JSON feed and and
 * adds it into the html head. 
 * @param {String} scriptSrc The URL for the script, assumed to already have at
 *     least one query parameter, so the '?' is not added to the URL
 * @param {String} scriptId The id to use for the script tag added to the head
 * @param {String} scriptCallback  The callback function to be used after the 
 *     JSON is retrieved.  The JSON is passed as the first argument to the 
 *     callback function.
 */
ilts.appendScriptTag = function(scriptSrc, scriptId, scriptCallback) {
  // Remove any old existance of a script tag by the same name
  var oldScriptTag = document.getElementById(scriptId);
  if (oldScriptTag) {
    oldScriptTag.parentNode.removeChild(oldScriptTag);
  }
  // Create new script tag
  var script = document.createElement('script');
  script.setAttribute('src', 
      scriptSrc + '&alt=json-in-script&callback=' + scriptCallback);
  script.setAttribute('id', scriptId);
  script.setAttribute('type', 'text/javascript');
  // Append the script tag to the head to retrieve a JSON feed of videos
  // NOTE: This requires that a head tag already exists in the DOM at the
  // time this function is executed.
  document.getElementsByTagName('head')[0].appendChild(script);
};
ilts.listVideos = function(queryType, searchTerm, page) {
	 
  ilts.previousSearchTerm = searchTerm; 
  ilts.previousQueryType = queryType;
  
  var queryUrl = ilts.QUERY_URL_MAP[queryType];
  if (queryUrl) {
    queryUrl += '?max-results=' + ilts.MAX_RESULTS_LIST +
        '&start-index=' + (((page - 1) * ilts.MAX_RESULTS_LIST) + 1);
    if (searchTerm != '') {
      queryUrl += '&q=' + searchTerm;
    }
    queryUrl += '&v=2&alt=jsonc';
    $.getJSON(queryUrl, function(feed) {
      var resultsTableContainer = document.getElementById("searchResultsVideoListTable");
      while (resultsTableContainer.childNodes.length >= 1) {
        resultsTableContainer.removeChild(resultsTableContainer.firstChild);
      }
      var resultsTable = document.createElement('table');
      resultsTable.setAttribute('class', ilts.VIDEO_LIST_CSS_CLASS);
      var tbody = document.createElement('tbody');
      resultsTable.setAttribute('width', '100%');
      resultsTableContainer.appendChild(resultsTable);

      $.each(feed.data.items, function (i, item) {
        //alert(item.title);
				ilts.appendVideoDataToTable(tbody, item, i);
				/*
        $("<img src = \""+item.thumbnail.sqDefault+"\" align=\"left\" />").appendTo('#searchResultsVideoListTable');
        $("<div class\""+ilts.VIDEO_LIST_CSS_CLASS+"\">"+item.title+"</p>").appendTo('#searchResultsVideoListTable');
        //$("<p>"+item.id+"</p>").appendTo('#searchResultsVideoListTable');
        
        $("<div class=\"video_descr\">"+item.description+"</p>").appendTo('#searchResultsVideoListTable');
        //$('#searchResultsVideoListTable').html('<p>' + item.id + '</p>'
        //+ '<p>' + item.title + '</p>');
				*/
      }); // FINE DEL EACH
			resultsTable.appendChild(tbody);
    });
    /*
    alert (queryUrl)
    ytvb.appendScriptTag(queryUrl, 
                         'searchResultsVideoListScript', 
                         'ytvb.listVideosCallback');
    */
    ilts.appendScriptTag(queryUrl, 
            'searchResultsVideoListScript', 
            'ilts.listVideosCallback');
    //ytvb.updateNavigation(page);
  } else {
    alert('Unknown feed type specified');
  }
};

ilts.renderTableResults= function (divContainer, feed) {

  var resultsTableContainer = document.getElementById(divContainer);

  // Deletes and re-adds the results table from container
  // NOTE: Any other elements added to the container will also be cleared
  while (resultsTableContainer.childNodes.length >= 1) {
    resultsTableContainer.removeChild(resultsTableContainer.firstChild);
  }

  var resultsTable = document.createElement('table');
  resultsTable.setAttribute('class', ilts.VIDEO_LIST_CSS_CLASS);
  var tbody = document.createElement('tbody');
  resultsTable.setAttribute('width', '100%');
  resultsTableContainer.appendChild(resultsTable);

  // Loops through entries in the feed and calls appendVideoData for each
  for (var i = 0, entry; entry = feed.entry[i]; i++) {
    // The entry.yt$noembed property will exist if this YouTube video does
    // not support viewing in an embedded player on a third-party site.  
    // Exclude these videos from listing here.  A feature request has been
    // submitted for an additional query parameter to exclude these results
    // from the initial results feed.
    if (! entry.yt$noembed) {
      ilts.appendVideoDataToTable(tbody, entry, i);
    }
  }
  resultsTable.appendChild(tbody);
}


ilts.appendVideoDataToTable = function(tbody, entry, entryIndex) {
  var tr = document.createElement('tr');


  var thumbnailTd = document.createElement('td');
  thumbnailTd.setAttribute('width', ilts.THUMBNAIL_WIDTH);
  var thumbnailImage = document.createElement('img');
  thumbnailImage.setAttribute('src', 
      entry.thumbnail.sqDefault);
  thumbnailImage.setAttribute('width', ilts.THUMBNAIL_WIDTH);
  thumbnailImage.setAttribute('height', ilts.THUMBNAIL_HEIGHT);
  thumbnailTd.appendChild(thumbnailImage);

  var metadataTd = document.createElement('td');
  metadataTd.setAttribute('class', "video_descr");
  metadataTd.setAttribute('width', '350');
  /*
  var metadataLink = document.createElement('a');
  metadataLink.setAttribute('href', '#'); 
  metadataLink.innerHTML = entry.title;
  */
  var titlePara = document.createElement('p');
  titlePara.setAttribute('class', "video_title");
  titlePara.innerHTML = entry.title;
  
  var descPara = document.createElement('p');
  descPara.innerHTML = (entry.description).substring(0,100);
  descPara.setAttribute('class', ytvb.VIDEO_DESCRIPTION_CSS_CLASS);
  metadataTd.appendChild(titlePara);
  metadataTd.appendChild(descPara);
  var operationTd=document.createElement('td');
  operationTd.setAttribute('class', "video_operation");
  operationTd.setAttribute('width', '100');
  var videoId=entry.id;
  //var videoId=entry.yt$videoid.$t;
  //ilts.showMessage(videoId);
  //operationTd.innerHTML = "<a class=\"links_add_video\" href=\"#\" id=\"add_video_"+videoId+"\"><img src=\"assets/icons/button_pink_heart.png\"></a>"+
  //"<a class=\"links_play_video\" href=\"#\" id=\"play_video_"+videoId+"\"><img src=\"assets/icons/audio_notification.png\"></a>";
  
  var buttonAddVideo = document.createElement('a');
  buttonAddVideo.setAttribute('href', '#'); 
  buttonAddVideo.setAttribute('class', 'links_add_video'); 
  buttonAddVideo.setAttribute('id', 'add_video'+videoId); 
  buttonAddVideo.innerHTML= "<img src=\"assets/icons/button_pink_heart.png\">";
  
  var buttonPlayVideo = document.createElement('a');
  buttonPlayVideo.setAttribute('href', '#'); 
  buttonPlayVideo.setAttribute('class', 'links_play_video'); 
  buttonPlayVideo.setAttribute('id', 'play_video'+videoId); 
  buttonPlayVideo.innerHTML= "<img src=\"assets/icons/audio_notification.png\">";
  buttonPlayVideo.onclick = ilts.generatePlayVideoLinkOnclick(entry.id.$t, entryIndex, 
		  ilts.REFERRING_FEED_TYPE_MAIN
		  //ilts.currentReferringFeedType
  );
  
  operationTd.appendChild(buttonAddVideo);
  operationTd.appendChild(buttonPlayVideo);
  //metadataLink.innerHTML = entry.title;
    
/*
  thumbnailTd.onclick = ytvb.generatePlayVideoLinkOnclick(entry.id.$t, entryIndex, 
		  //ytvb.REFERRING_FEED_TYPE_MAIN
		  ytvb.currentReferringFeedType
  );
  metadataTd.onclick = ytvb.generatePlayVideoLinkOnclick(entry.id.$t, entryIndex, 
		  //ytvb.REFERRING_FEED_TYPE_MAIN
		  ytvb.currentReferringFeedType
  );
*/
  //operationTd.onclick =ytvb.saveVideo(videoId);
  
  tr.appendChild(thumbnailTd);
  tr.appendChild(metadataTd);
  tr.appendChild(operationTd);
  tbody.appendChild(tr);
  
  
};


ilts.showMessage = function(message) {
  alert(message);
};

ilts.openFormAddSong = function() {
  $(".links_add_video").dialog();
}

/**
 * Returns a function that can be added as an event handler for playing
 * a video upon the firing of the event.
 * @param {String} videoUrl The URL of the video to play
 * @param {Number} entryIndex The index of the entry in the referring feed
 * @param {String} referringFeed The referring feed
 * @return {Function} The video playing function
 */
ilts.generatePlayVideoLinkOnclick = function(videoUrl, 
                                             entryIndex, 
                                             referringFeed) {
  return function() {
    ilts.playVideo(entryIndex, referringFeed);
    return false;
  };
};

/**
 * Adds the object and embed tags to play the specified video
 * @param {Number} entryIndex The index of the video in the referring feed
 * @param {String} referringFeed Name of the referring feed
 */
ilts.playVideo = function(entryIndex, referringFeed) {
  var entry;
  try {
    if (referringFeed == ytvb.REFERRING_FEED_TYPE_RELATED) {
      entry = ilts.jsonFeedRelated_.entry[entryIndex];
    } else if (referringFeed == ytvb.REFERRING_FEED_TYPE_USER) {
      entry = ilts.jsonFeedUser_.entry[entryIndex];
    } else if (referringFeed == ytvb.REFERRING_FEED_TYPE_MAIN) {
      entry = ilts.jsonFeed_.entry[entryIndex];
    } else {
      throw "Unknown type of referring feed.";
    }
    var videoHref = ilts.findMediaContentHref(entry, ilts.FLASH_MIME_TYPE);
    var videoPlayerDiv = document.getElementById(ilts.VIDEO_PLAYER_DIV);
    // Add standard YouTube video embed code, with standard height/width
    // values.  Enable autoplay of the video.
    var html = [];
    html.push('<b>');
    html.push(entry.media$group.media$title.$t);
    html.push('</b><br />');
    html.push('<object width="'+ilts.VIDEO_PLAYER_WIDTH+'" height="'+ilts.VIDEO_PLAYER_HEIGHT+'"><param name="movie" value="');
    html.push(videoHref);
    html.push('&autoplay=1"></param><param name="wmode" value="transparent">');
    html.push('</param><embed src="');
    html.push(videoHref);
    html.push('&autoplay=1" type="application/x-shockwave-flash" ');
    html.push('wmode="transparent" width="'+ilts.VIDEO_PLAYER_WIDTH+'" height="'+ilts.VIDEO_PLAYER_HEIGHT+'"></embed></object>');
    videoPlayerDiv.innerHTML = html.join('');
    ilts.showRelatedVideos(entryIndex, referringFeed);
    if (entry.author && entry.author.length > 0) {
      ilts.showVideosByUser(entry.author[0].uri.$t);
    }
  } catch (err) {
    alert(err);
  }
};

/**
 * Callback function used for processing the results of ytvb.listVideos.
 * This function calls appendVideoData to list each of the videos in the UI
 * @param {Object} data The object obtained by evaluating the JSON text 
 *     returned by the YouTube data API
 */
ilts.listVideosCallback = function(data) {
  // Stores the json data returned for later lookup by entry index value
  ilts.jsonFeed_ = data.feed;
  ilts.currentReferringFeedType = ilts.REFERRING_FEED_TYPE_MAIN;
  ilts.renderTableResults(ilts.VIDEO_LIST_TABLE_CONTAINER_DIV, data.feed);
  
/*
  $(".links_add_video").fancybox({
      'width' : '75%',
      'height' : '75%',
      'autoScale' : false,
      'transitionIn' : 'none',
      'transitionOut' : 'none',
      'type': 'iframe'
    });
*/
};

